<?php
namespace app\admin\controller\customer;

use app\common\model\SystemCustomer;
use library\Controller;
use think\Db;

/**
 * 跟进一览
 * Class Follow
 * @package app\admin\controller\customer
 */
class Follow extends Controller
{
     /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SystemCustomerFollows';	
	
    /**
     * 跟进一览
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '跟进一览';
        $where = [];            
		$where[] = ['is_deleted','eq',0];
		$user_id = intval(session('admin_user.id'));
		if($user_id != '10000'){
			$where[] = ['charger','eq',$user_id];
		}
		$dep_user =  dep_users(1);
		$this->charger_op = assemble_op([''=>'-- 全部负责人 --'], $dep_user);   		   
        $this->source_type_op = assemble_op([''=>'-- 全部来源渠道 --'], get_all_options('source_type'));       
        $this->transaction_op = assemble_op([''=>'-- 全部是否成交 --'], get_all_options('transaction'));
			   
		$query = $this->_query($this->table)->like('customer_unique,company_name')->equal('charger,source_type,transaction');    
		$query->where($where)->order('id desc')->dateBetween('create_at,follow_at')->page();
        
    }
    
    
    /**
     * 列表数据处理
     * @auth true
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {
    	$country = get_all_options('country');
    	$source_type = get_all_options('source_type');
    	$transaction = get_all_options('transaction');
    	foreach ($data as &$vo) {       	
        	$vo['charger_cn'] = $vo['charger'] ? user_list()[$vo['charger']] : '';
			$vo['source_type_cn'] = $source_type[$vo['source_type']];
			$vo['transaction_cn'] = $transaction[$vo['transaction']];
        }		
    }
    
    /**
     * 根据客户ID获取客户联系人
     */
    public function link_name()
	{
		$customer_id = $this->request->param('customer_id');
		$where = [];            
		$where[] = ['is_deleted','eq',0];
		$where[] = ['status','eq',1];
		$where[] = ['id','eq',$customer_id];
		$user_id = intval(session('admin_user.id'));
		if($user_id != '10000'){
			$where[] = ['charger','eq',$user_id];
		}
		$link_name = Db::name('system_customer')->where($where)->value('link_name');	
		if(!$link_name){
			$this->error('获取失败，客户不存在或已进入公海');
		}	
		$this->success('获取成功',$link_name);			
	}
    
    /**
     * 添加跟进
     * @auth true
     *
     */
    public function addFollow()
    {
        if ($this->request->isGet()) {
        	$where = [];            
			$where[] = ['is_deleted','eq',0];
			$where[] = ['status','eq',1];
			$user_id = intval(session('admin_user.id'));
			if($user_id != '10000'){
				$where[] = ['charger','eq',$user_id];
			}
            $customers = Db::name('system_customer')->where($where)->field('id,unique,company_name')->order('id desc')->select();
            foreach($customers as $k=>$v){
            	$customers[$k]['name'] = $v['unique'].'--'.$v['company_name'];
            	unset($customers[$k]['unique']);
            	unset($customers[$k]['company_name']);
            }
       		
            $this->customers = $customers;
            
//          $this->source_types = get_normal_options('source_type');
            $this->transactions = get_normal_options('transaction');
            
            $this->fetch('follow_add');
        } else {
            $parameter = $this->request->post();
            $customer = Db::name('system_customer')->where(['id' => $parameter['customer_id'],'status'=>1,'is_deleted'=>0])->field('id,unique,company_name,link_name,source_type,charger,follow_num')->find();
            if(!$customer){
            	$this->error('客户不存在或已进入公海');
            }    
            $user_id = intval(session('admin_user.id'));
			if($user_id != '10000'){
				if($customer['charger'] != $user_id){
					$this->error("不是自己客户，无法添加");
				}
			}
            Db::startTrans();
            try {           	
				$data = [];
	            $data['customer_id'] = $parameter['customer_id'];
	            $data['customer_unique'] = $customer['unique'];
	            $data['company_name'] = $customer['company_name'];
	            $data['link_name'] = $parameter['link_name'];
	            $data['source_type'] = $customer['source_type'];
	            $data['transaction'] = $parameter['transaction'];
	            $data['follow_at'] = $parameter['follow_at'];
	            $data['content'] = $parameter['content'];
	            $data['charger'] = $customer['charger'];
	            $data['creater'] = intval(session('admin_user.id'));
	            $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s',time());
	            Db::name($this->table)->insert($data);
	            
	            //更改客户信息
	            $end_at = get_futuredate(get_customer_config(1,'expire_day'));
	            $follow_num = $customer['follow_num'] + 1;
	            Db::name('system_customer')->where(['id' => $parameter['customer_id']])->update(['end_at'=>$end_at,'follow_num'=>$follow_num,'last_follow_at'=>$parameter['follow_at']]);
	            
	            sysoplog('跟进一览', '新增'.$customer['company_name'].'跟进记录成功');
				operatelog($customer['id'],'SystemCustomer','添加了一条跟进记录');
                Db::commit();
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保存失败，请重试');
            }
            
            $this->success('保存成功');
        }
    }
    
    
    
    /**
     * 编辑跟进
     * @auth true
     *
     */
    public function editFollow()
    {
        if ($this->request->isGet()) {
            $parameter = $this->request->get();
            $follow = Db::name($this->table)->where(['id' => $parameter['id'],'is_deleted'=>0])->find();
            if(!$follow){
            	$this->error('跟进ID错误');
            } 
            $this->customer_id = $follow['customer_id'];
            $this->transactions = get_all_options('transaction');
            $this->info = $follow;
            $this->fetch('follow_edit');
        } else {
            $parameter = $this->request->post();
            $follow = Db::name($this->table)->where(['id' => $parameter['id'],'is_deleted'=>0])->find();
            if(!$follow){
            	$this->error('跟进不存在');
            } 
            $customer = Db::name('system_customer')->where(['id' => $parameter['customer_id'],'status'=>1,'is_deleted'=>0])->field('id,company_name,link_name,charger,follow_num')->find();
            if(!$customer){
            	$this->error('客户不存在或已进入公海');
            }    
            $user_id = intval(session('admin_user.id'));
			if($user_id != '10000'){
				if($customer['charger'] != $user_id){
					$this->error("不是自己客户，无法编辑");
				}
			}
            Db::startTrans();
            try {           	
				$data = [];
	            $data['link_name'] = $parameter['link_name'];	            	
	            $data['transaction'] = $parameter['transaction'];
	            $data['follow_at'] = $parameter['follow_at']; 
	            $data['content'] = $parameter['content'];   
	            $data['updated_at'] = date('Y-m-d H:i:s',time());          
	            Db::name($this->table)->where(['id'=>$parameter['id']])->update($data);
	            	            
	            //获取客户的最后一条跟进
	            $last_follow = Db::name($this->table)->where(['customer_id' => $parameter['customer_id'],'is_deleted'=>0])->order('id desc')->find();
	            if($last_follow['id'] == $parameter['id']){
	            	//更改客户信息
//		            $end_at = get_futuredate(get_customer_config(1,'expire_day'));		            
		            Db::name('system_customer')->where(['id' => $parameter['customer_id']])->update(['last_follow_at'=>$parameter['follow_at']]);	            	
	            }
	            sysoplog('跟进一览', '编辑'.$customer['company_name'].'跟进记录成功');
	            operatelog($customer['id'],'SystemCustomer','编辑了一条跟进记录');
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保存失败，请重试');
            }
            
            $this->success('保存成功');
        }
    }
    
    
    /**
     * 删除跟进
     * @auth true
     */
    public function remove()
    {	
        $id = $this->request->post('id');	
    	$follow = Db::name($this->table)->where(['id'=>$id,'is_deleted'=>0])->find();
    	if(!$follow){
        	$this->error('跟进不存在');
        }
        $customer = Db::name('system_customer')->where(['id' => $follow['customer_id'],'status'=>1,'is_deleted'=>0])->field('id,company_name,charger,follow_num')->find();
        if(!$customer){
        	$this->error('客户不存在或已进入公海');
        }
    	$user_id = intval(session('admin_user.id'));
		if($user_id != '10000'){
			if($customer['charger'] != $user_id){
				$this->error("不是自己客户，无法删除");
			}
		}
		
		Db::startTrans();
        try {           	          
            Db::name($this->table)->where(['id'=>$id])->update(['is_deleted'=>1]);
            //获取客户的最后一条跟进
            $last_follow = Db::name($this->table)->where(['customer_id' => $follow['customer_id'],'is_deleted'=>0])->order('id desc')->find();
            $last_follow_at = $last_follow ? $last_follow['follow_at'] : '';
            $follow_num = $customer['follow_num'] - 1;
            Db::name('system_customer')->where(['id' => $follow['customer_id']])->update(['last_follow_at'=>$last_follow_at,'follow_num'=>$follow_num]);	            		
            sysoplog('跟进一览', '删除'.$customer['company_name'].'跟进记录成功');
	        operatelog($customer['id'],'SystemCustomer','删除了一条跟进记录');            	
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('删除失败，请重试');
        }
		
		$this->success('删除成功');
    }
    
    
   
	
	
    
    /**
     * 导出公司
     * @auth true
     */
//  public function export()
//  {  	
//  	$data = $this->request->param();
//  	$ids = explode(',', $data['id']);
//  	$list = CompanyService::export_company($ids);
//  	toexcel($list['filename'],$list['titles'],$list['list']);   	 	      
//  }
    

}
